package svc

import (
	"log"
	"os"
	"time"

	"github.com/iriver/ai-offer/backend/internal/config"
	"github.com/iriver/ai-offer/backend/internal/model"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// ServiceContext 服务上下文，用于管理依赖项
type ServiceContext struct {
	Config    config.Config
	DB        *gorm.DB
	Redis     *redis.Redis
	UserStore model.UserStore
}

// NewServiceContext 创建服务上下文
func NewServiceContext(c config.Config) *ServiceContext {
	// 设置GORM日志
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Millisecond * 200,
			LogLevel:      getGormLogLevel(c.Database.LogLevel),
			Colorful:      true,
		},
	)

	// 初始化数据库连接
	db, err := gorm.Open(postgres.Open(c.Database.Source), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		logx.Errorf("连接数据库失败: %v", err)
		panic(err)
	}

	// 配置连接池
	sqlDB, _ := db.DB()
	sqlDB.SetMaxIdleConns(c.Database.MaxIdleConn)
	sqlDB.SetMaxOpenConns(c.Database.MaxOpenConn)
	sqlDB.SetConnMaxLifetime(time.Hour)

	// 自动迁移模型（开发环境可以使用，生产环境应当使用手动迁移）
	if c.Mode == "dev" {
		err = db.AutoMigrate(&model.UserModel{})
		if err != nil {
			logx.Errorf("自动迁移模型失败: %v", err)
			panic(err)
		}
	}

	// 初始化Redis
	rds := redis.New(c.Redis.Host, func(r *redis.Redis) {
		r.Type = c.Redis.Type
		r.Pass = c.Redis.Pass
	})

	return &ServiceContext{
		Config:    c,
		DB:        db,
		Redis:     rds,
		UserStore: model.NewUserStore(db),
	}
}

// 获取GORM日志级别
func getGormLogLevel(level string) logger.LogLevel {
	switch level {
	case "silent":
		return logger.Silent
	case "error":
		return logger.Error
	case "warn":
		return logger.Warn
	case "info":
		return logger.Info
	default:
		return logger.Info
	}
}
